import {useState,useEffect} from 'react'

import jdManagement from './JdManagement.module.less'
import { Link } from "react-router-dom";
import TagManage from './component/TagManage.jsx'
import RequireManage from './component/RequireManage.jsx'

import {searchTagList, 
        addTag, 
        searchRequireDescriptionList, 
        updateRequireDescriptionItem
    } from '../../api/index.js'



export default function JdManagement(){
    useEffect(()=>{
        async function searchList() {
            await updateTags()
            await refreshRequireDescription()
        }
        searchList()
    },[])



    const [tags,setTags] = useState([])
    const [requireDescription,setRequireDescription] = useState([])


    // 更新标签信息
    const updateTags =async ()=>{
        let result = await searchTagList()
        setTags(result)
    }

    // 更新需求描述
    const refreshRequireDescription = async () =>{
        let result = await searchRequireDescriptionList()
        setRequireDescription(result)
    }


    const handleAddTag= async()=>{
        let id = tags[tags.length - 1]?.id + 1|| 1;
        await addTag({
            id: id,
            name:`未命名${id}`,
        })
        updateTags()
    }

    const handleEditTag=(id,value)=>{
        setTags(tags.map(item=>{
            if(item.id === id){
                return {...item,name:value}
            }else{
                return item
            }

        }))
    }

    const handleUpdateRequireDescription= async (params)=>{
        await updateRequireDescriptionItem(params)
    }

    return (
         <div className={jdManagement.jdManagement}>
            <div className={jdManagement.bar}>
                <span > <Link to={`/`}>返回</Link></span>
            </div>
            <div className={jdManagement.main}>
                <TagManage tags={tags} onAddTag={handleAddTag} onEditTag={handleEditTag} onUpdateTag={updateTags} />
                <RequireManage 
                    refreshRequireDescription={refreshRequireDescription} 
                    updateRequireDescription={handleUpdateRequireDescription} 
                    tags={tags} 
                    requireDescription={requireDescription} 
                />
            </div>
        </div>
    )
}